<template>
  <div>
    <div class="table-data" v-show="tabShow"
    >
      <div class="search-box">
        <el-button size="small" type="primary"  @click="handleAdd"><i class="el-icon-plus"></i>添加规则</el-button>
      </div>
      <el-table
      v-loading="loading"
      element-loading-text="正在加载"
      element-loading-spinner="el-icon-loading" :data="tableData" :header-cell-style="headClass" :height="tHeight"  style="width:100%"  class="table-box">
        <el-table-column label="id" width="80" prop="id"></el-table-column>
        <el-table-column label="规则名称"  prop="title"></el-table-column>
        <el-table-column label="企业名称"  prop="merchant.name"></el-table-column>
        <el-table-column label="返现规则" >
          <template slot-scope="scope">
                <p v-for="(item,index) in scope.row.config" :key="index">
                  充{{item.charge_amount}}送{{item.give_amount}}
                </p>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <el-button size="small" @click="handleEdit(scope.row)" type="primary" >修改</el-button>
            <el-button size="small" @click="handleDel(scope.row.id)" type="danger" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pages" ref="page-box">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-sizes="[10,30,50]"
        :page-size="size"
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"
      ></el-pagination>
      </div>
    </div>
    <router-view @loadData="loadData" :tabShow="tabShow"></router-view>

    <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="50%"
   >
        <el-form
        label-width="100px"
        :rules="rules"
        label-position="right"
        style="width:600px;"
        :model="addObj"
        ref="ruleForm"
      >
        <el-form-item label="选择企业" prop="mch_id">
          <el-select v-model="addObj.mch_id">
              <el-option v-for="(item,index) in companyList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规则名称" prop="title">
          <el-input v-model="addObj.title" autocomplete="off"  size="small"></el-input>
        </el-form-item>

        <div>
          <div v-for="(item, index) in addObj.config" :key="index">
              <el-row>
                  <el-col :span="8">
                      <el-form-item label="充值：" prop="charge_amount">
                          <el-input v-model="item.charge_amount" size="small" placeholder="充值" >

                          </el-input>
                      </el-form-item>
                  </el-col>
                  <el-col :span="8">
                      <el-form-item label="赠送：" prop="give_amount">
                          <el-input v-model="item.give_amount" size="small" placeholder="赠送" ></el-input>
                      </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="">
                          <el-button size="small" type="danger" @click="move(index)">删除</el-button>
                      </el-form-item>

                  </el-col>
              </el-row>
          </div>
        </div>
      <el-form-item label="">
          <el-button size="small" type="success" @click="addConfig()">新增档位</el-button>
        </el-form-item>
      </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel('ruleForm')" size="small">取 消</el-button>
      <el-button type="primary" @click="submit('ruleForm')" size="small">确 定</el-button>
    </span>
</el-dialog>

  </div>
</template>

<script lang="ts">
import { Component, Vue, Provide,Prop,Watch } from "vue-property-decorator";
import companyApi from "@/api/company";
@Component({
  components: { }
})
export default class conpanyRules extends Vue {
  // @Getter("user") getUser: any;
  @Provide() state: string = "1"; // 状态默认值
  @Provide() tableData: any = []; // 表格数据
  @Provide() tHeight: number = document.body.offsetHeight - 323;
  @Provide() page: number = 1; // 当前page
  @Provide() size: number = 10; // 请求数据的个数 默认5
  @Provide() total: number = 0; // 总数据条数
  @Provide() tabShow: Boolean = true; // 是显示否列表页面
  @Provide() loading: Boolean = true; // 是否显示加载图标
  @Provide() status: number = 0;//禁用状态
  @Provide() title: string ="";
  @Prop({}) tabVisible!: any;
  @Provide() dialogVisible: Boolean = false;
  @Provide() companyList: any = [];
  @Provide() addObj: any = {
    id:'',
    mch_id : '',
    title:'',
    config:[
      {
        charge_amount:'',
        give_amount:''
      }
    ]
  };
  @Provide() searchMap:{
    keyword: string
  }={
    keyword: "",
  }
  rules: any= {
    mch_id: [{ required: true, message: "请选择企业", trigger: "change" }],
    title: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  }
  @Watch("$route") handleRouteChange(to: any,form:any) {
    if(form.path!='/ruleList'){
      this.tabShow=this.tabVisible;
    }
  }

  headClass() {
    return "text-align: center;background:#eef1f6;";
  }

  created() {
    this.loadData();

    this.loadCompany();
    if(this.$route.path!='/ruleList'){
      this.tabShow=false
    }

  }
  move(index) {
    this.$confirm(`确实删除吗`, "是否继续?", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      closeOnClickModal:false
    })
      .then(() => {
        this.addObj.config.splice(index, 1);
        this.$message.success("删除成功");
      })
      .catch(() => {});
  }

  handleDel(id) {
    this.$confirm('确定要删除该充送规则吗', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
       closeOnClickModal:false
    }).then(() => {
      companyApi.ruleDelete({id})
      .then((res:any)=>{
        if(res.data.code==200){
          this.$message({
            message: '操作成功',
            type: "success"
          });
          this.loadData();
        }
      });
    }).catch(() => {
      this.$message({
        type: 'info',
        message: '已取消'
      });          
    });


   
  }

  addConfig(){
    this.addObj.config.push(
      {
        charge_amount:'',
        give_amount:''
      }
    )
  }
  handleAdd(){
    this.title = '添加'
    this.resetForm(null);
    this.dialogVisible = true
  }

  handleEdit(row){
    this.title = '修改'
    this.resetForm(row)
    this.dialogVisible = true
  }
  resetForm(row){
      this.addObj.id = row ? row.id:null;
      this.addObj.mch_id = row ? row.mch_id: '';
      this.addObj.title = row ? row.title: '';
      this.addObj.config = row ? row.config : [
      {
        charge_amount:'',
        give_amount:''
      }
    ]
  }

  loadData() {
    companyApi.chargeRules(this.page,this.size)
      .then((res: any) => {
        this.tableData = res.data.data.list;
        this.total = res.data.data.total;
        this.loading=false
      });
  }

  loadCompany(){
    companyApi.list(1,9999).then((res: any) => {
      this.companyList = res.data.data.list;
    })
  }

  handleSizeChange(val: number): void {
    this.size = val;
    this.page = 1;
    this.loadData();
  }
  submit(formName:any){
    (this.$refs[formName] as any).validate((valid: boolean) => {
      let config = this.addObj.config
      for(let i=0;i<config.length;i++) {
        if(config[i].charge_amount=='') {
          this.$message({
            message: '请输入充值金额',
            type: "error"
          });
          valid=false
          return false
        }
        if(config[i].give_amount=='') {
          this.$message({
            message: '请输入赠送金额',
            type: "error"
          });
          valid=false
          return false
        }
      }
      if(valid) {
        companyApi.chargeRulesEdit(this.addObj).then((res: any) => {
          const resp = res.data;
          if(resp.code !== 200){
            this.$message.error(resp.msg)
            return false;
          }
          this.$message.success(this.title + '成功');
          this.loadData();
          this.dialogVisible = false
        })
      }
    })
  }
  
  handleCurrentChange(val: number): void {
    this.page = val;
    this.loadData();
  }

  handleSearch(): void {
    // 点击搜索
  this.page = 1;
  this.loadData();
  }
  cancel(formName:any) {
    (this.$refs[formName] as any).resetFields();
    this.dialogVisible = false
  }
}
</script>

<style lang="scss" scoped>
.el-date-editor{
  margin-right: 10px;
}
</style>
